首页 > 试题广场 >

求1+2+3+...+n

[编程题]求1+2+3+...+n
  • 热度指数:370572 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

数据范围:
进阶: 空间复杂度 ,时间复杂度
示例1

输入

5

输出

15
示例2

输入

1

输出

1
推荐
class Solution {
public:
    int Sum_Solution(int n) {
        int ans = n;
        ans && (ans += Sum_Solution(n - 1));
        return ans;
    }
};

编辑于 2015-06-19 17:53:23 回复(107)
# 递归
class Solution:
    def Sum_Solution(self , n: int) -> int:
        if n == 1:
            return 1
        sum = n
        sum += self.Sum_Solution(n-1)
        return sum

发表于 2022-07-20 23:33:22 回复(0)
class Solution:
    def Sum_Solution(self , n: int) -> int:
        # write code here
        return int(eval('(1+n)*n/2'))

发表于 2022-04-27 09:42:13 回复(0)
一行代码搞定,他又没规定不能用内置函数
import operator
from functools import reduce
class Solution:
    def Sum_Solution(self , n: int) -> int:
        # write code here
        return reduce(operator.add, range(1,n+1))
发表于 2022-04-18 10:51:58 回复(0)
Python双函数,n=1时调匿名函数
class Solution:
    def Sum_Solution(self , n: int) -> int:
        func_arr, offset = [lambda x:1, self.Sum_Solution], [0, n]
        return offset[min(n - 1, 1)] + func_arr[min(n - 1, 1)](n - 1)


发表于 2022-02-27 20:37:51 回复(0)
class Solution:
    def Sum_Solution(self , n: int) -> int:
        a = range(1, n+1)
        return sum(a)

发表于 2021-12-01 09:02:14 回复(0)
return sum(range(1,n+1))
发表于 2021-09-03 16:37:23 回复(0)
递归
发表于 2021-08-31 14:19:39 回复(0)
python 版本
整体思路是使用递归求解:f(n) = n + f(n-1)
关键在于如何停止递归,思想如下:
当n > 0时,对n取两次非为True;当n == 0时,对n取两次非为False。
由于不能使用if判断,因此将递归函数和终止函数分开写,并使用数组保存,然后将上面对n的判断结果作为数组下标来选择使用哪个函数。
整体代码如下:
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.choice = ['Solution().StopCur(n-1)', 'Solution().Sum_Solution(n-1)']
        
    def Sum_Solution(self, n):
        # write code here
        return n + eval(self.choice[not not n])
    
    def StopCur(self, n):
        return 0


发表于 2021-08-25 17:47:32 回复(0)
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return n and n+self.Sum_Solution(n-1)
        
        
        

发表于 2021-08-09 01:03:47 回复(0)
#这题凭啥难度中等啊
class Solution:
    def Sum_Solution(self, n):
        return int((n+1)*n/2)
发表于 2021-08-04 10:34:17 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here\
        if n == 1:
            return 1
        return self.Sum_Solution(n-1) + n
#挺像阶乘的做法 反正把问题变成更小的问题 然后找到终止条件也就是n = 1的时候。

发表于 2021-07-29 22:16:44 回复(0)

问题信息

难度:
12条回答 130154浏览

热门推荐

通过挑战的用户

查看代码